package com.tingyuge.base.thread.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 关于lock 与synchronize关键字在锁的处理方式上的区别
 */
public class LockTest1 {

    private Lock lock = new ReentrantLock();

    public void MyMethod1() {
        try {
            lock.lock();

            System.out.println("LockTest1.MyMethod1");
        } finally {
//            lock.unlock();
        }

    }

    public void MyMethod2() {
      /*  try {
            lock.lock();
            System.out.println("LockTest1.MyMethod2");

        } finally {
            lock.unlock();
        }*/
        boolean result = false;
        try {
            result = lock.tryLock(800, TimeUnit.MILLISECONDS);
            if(result){
                System.out.println("method2");
            }else{
                System.out.println("method2 没有获取锁");
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        LockTest1 lockTest1 = new LockTest1();


        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                lockTest1.MyMethod1();
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        });


        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                lockTest1.MyMethod2();
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        });

        t1.start();
        t2.start();
    }
}
